package abg.manage.controller.jy;

import abg.core.common.security.Auth;
import abg.core.common.util.MinioKit;
import abg.core.common.util.StringKit;
import abg.core.domain.db.AaFile;
import abg.core.domain.search.TCourseFilePsh;
import abg.core.domain.sys.SRS;
import abg.core.service.jldz.JldzService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;

import static abg.core.domain.db.table.AaXqCjTableDef.AA_XQ_CJ;

/**
 * 文件处理
 */
@Slf4j
@RestController
@RequestMapping("/manage/jldz")
public class FileC {
    @Resource
    private JldzService jldzService;
    @Resource
    private MinioKit minioKit;

    /**
     * 上传文件
     */
    @Auth(role = {"40", "50"})
    @PostMapping(value = "/ddUpload")
    public SRS<Object> ddUpload(@RequestParam("file") MultipartFile file, @RequestHeader String token, long chunkIndex,
                                String taskType, String taskId, String cjNumber) throws Exception {

        String s = minioKit.uploadGetURI(file.getInputStream(), file.getName(), file.getContentType());

        log.error(" 上传结果 " + s);

//        String bucketName = "your-bucket-name";
//        String objectName = "fileName";
//        int totalChunks = 10; // 假设有10个分块文件
//
//        try {
//            List<InputStream> chunkStreams = new ArrayList<>();
//
//            // 逐个获取分块文件的流并加入列表
//            for (int i = 0; i < totalChunks; i++) {
//                InputStream chunkStream = minioClient.getObject(
//                        GetObjectArgs.builder()
//                                .bucket(bucketName)
//                                .object(objectName + "_" + i)
//                                .build()
//                );
//                chunkStreams.add(chunkStream);
//            }
//
//            // 合并文件
//            InputStream mergedInputStream = new SequenceInputStream(java.util.Collections.enumeration(chunkStreams));
//
//            // 将合并后的文件流上传至MinIO
//            ObjectWriteResponse response = minioClient.putObject(
//                    PutObjectArgs.builder()
//                            .bucket(bucketName)
//                            .object(objectName)
//                            .stream(mergedInputStream, mergedInputStream.available(), -1)
//                            .build()
//            );
//
//            // 关闭流
//            for (InputStream stream : chunkStreams) {
//                stream.close();
//            }
//            mergedInputStream.close();
//
//            return "File merged and uploaded successfully to MinIO with ETag: " + response.etag();
//        } catch (IOException | ErrorResponseException | InsufficientDataException
//                 | InternalException | InvalidBucketNameException | InvalidKeyException
//                 | InvalidResponseException | NoSuchAlgorithmException | ServerException
//                 | XmlParserException e) {
//            e.printStackTrace();
//            return "File merging and upload failed: " + e.getMessage();
//        }
//    }
//
//        AaFile sysFile = jldzService.uploadAnyFile(file, token, taskType, taskId, cjNumber);
//        return SRS.bySuccess(sysFile);
        return SRS.bySuccess(s);
    }

    /**
     * 上传文件
     */
    @Auth(role = {"40", "50"})
    @PostMapping(value = "/uploadFile")
    public SRS<AaFile> uploadFile(@RequestPart("file") MultipartFile file, @RequestHeader String token, String taskType, String taskId, String cjNumber) throws IOException {
        AaFile sysFile = jldzService.uploadAnyFile(file, token, taskType, taskId, cjNumber);
        return SRS.bySuccess(sysFile);
    }

    /**
     * 教师删除自身文件
     */
    @Auth(role = {"40"})
    @PostMapping(value = "/js/deleteFile")
    public SRS<Object> deleteFile(String ids) {
        jldzService.deleteFile(ids);
        return SRS.bySuccess();
    }

    //课程任务文件
    @Auth(role = {"40"})
    @PostMapping("/jsTaskFile")
    public SRS<Page<AaFile>> jsTaskFile(TCourseFilePsh pageSearch) {
        pageSearch.setJsNumber(jldzService.getJsNumber());
        Page page = jldzService.taskFile(pageSearch);
        return SRS.bySuccess(page);
    }

    //课程任务文件
    @Auth(role = {"50"})
    @PostMapping("/bmTaskFile")
    public SRS<Page<AaFile>> bmTaskFile(TCourseFilePsh pageSearch) {
        pageSearch.setBmCode(jldzService.getBmCode());
        Page page = jldzService.taskFile(pageSearch);
        return SRS.bySuccess(page);
    }

    //课程任务文件
    @Auth(role = {"60"})
    @PostMapping("/jwTaskFile")
    public SRS<Page<AaFile>> jwTaskFile(TCourseFilePsh pageSearch) {
        Page page = jldzService.taskFile(pageSearch);
        return SRS.bySuccess(page);
    }

    /**
     * 教务处角色：下载压缩包文件
     */
    @Auth(role = {"60"})
    @RequestMapping("/jw/downloadZip")
    public void jwDownloadZip(String taskIds, String cjNumbers, String type) throws Exception {
        ArrayList<String> cjNumberList = StringKit.split(cjNumbers);
        //教务处随便查
        QueryWrapper wrapper = QueryWrapper.create().and(AA_XQ_CJ.NUMBER.in(cjNumberList));
        jldzService.jwDownloadZip(taskIds, cjNumbers, type, wrapper);
    }

    /**
     * 部门角色：下载压缩包文件
     */
    @Auth(role = {"50"})
    @RequestMapping("/bm/downloadZip")
    public void bmDownloadZip(String cjNumbers, String type) throws Exception {
        ArrayList<String> cjNumberList = StringKit.split(cjNumbers);
        //部门只能查自己的
        QueryWrapper wrapper = QueryWrapper.create()
                .and(AA_XQ_CJ.BM_CODE.eq(jldzService.getBmCode()))
                .and(AA_XQ_CJ.NUMBER.in(cjNumberList));
        jldzService.jwDownloadJsZip(cjNumbers, type, wrapper);
    }


}
